package org.goodsmanager.controller;

import org.goodsmanager.entity.User;
import org.goodsmanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 密码测试控制器（仅用于开发环境）
 */
@Controller
@RequestMapping("/test")
public class PasswordTestController {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    @Autowired
    private UserService userService;

    /**
     * 测试常见密码
     */
    @GetMapping("/test-passwords")
    @ResponseBody
    public Map<String, Object> testPasswords(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 从数据库获取admin用户的密码哈希值
        User adminUser = userService.getUserByUsername("admin");
        if (adminUser == null) {
            result.put("error", "Admin user not found in database");
            return result;
        }
        
        String hashedPassword = adminUser.getPassword();
        
        // 常见密码列表
        String[] commonPasswords = {
            "admin", "admin123", "123456", "password", "root", "goodsmanager", 
            "goods123", "manager", "test", "123", "1234", "12345", "qwerty",
            "goods", "goodsadmin", "gmadmin", "gms123", "goodsmanager123",
            "system", "sysadmin", "sa", "pass", "pass123", "admin@123",
            "Admin123", "ADMIN", "ADMIN123", "GoodsManager", "GoodsManager123"
        };
        
        Map<String, Boolean> passwordResults = new HashMap<>();
        for (String password : commonPasswords) {
            boolean matches = passwordEncoder.matches(password, hashedPassword);
            passwordResults.put(password, matches);
            if (matches) {
                result.put("foundPassword", password);
            }
        }
        
        result.put("passwordTests", passwordResults);
        result.put("hashedPassword", hashedPassword);
        
        return result;
    }
}